<?php
namespace app\api\service;
use app\common\model\User;
use think\exception\ValidateException;
use think\facade\Cache;

class VipService{
    const DISCUZ_VISIT_NUM = 'DISCUZ_VISIT_NUM';
    const FORUM_VISIT_NUM = 'FORUM_VISIT_NUM';
    const HIGHEND_VISIT_NUM = 'HIGHEND_VISIT_NUM';

    private function visit(User $userinfo, string $type, string $name) {
        $visitNum = $this->getVisitNum($type);
        $userVip = $userinfo->userVip();

        if (empty($userVip)) {
            throw new ValidateException("该资源需要会员才能查看");
        }

        

        $usableField = 'usable_' . strtolower(str_replace('_VISIT_NUM', '', $type)) . '_num';
        if($userVip[$usableField] == 0){
            throw new ValidateException('你没有权限访问该资源，请升级到更高的会员');
        }
        
        if ($userVip[$usableField] < $visitNum) {
            $msg = $userVip['expire_day_num'] > 0 
                ? "您今日的[{$name}]访问次数不足,请升级到更高的会员" 
                : "您今日的[{$name}]访问次数己达到上限";
            throw new ValidateException($msg);
        }
        $this->setVisitNum($type, $visitNum + 1);
    }

    public function visitDiscuz(User $userinfo) {
        $this->visit($userinfo, self::DISCUZ_VISIT_NUM, '开放论坛');
    }

    public function visitForum(User $userinfo) {
        $this->visit($userinfo, self::FORUM_VISIT_NUM, '经典凤楼');
    }

    public function visitHighend(User $userinfo) {
        $this->visit($userinfo, self::HIGHEND_VISIT_NUM, '高端优质');
    }

    public function getVisitNum($key) {
        $visitNum = Cache::get($key. "_". date('Ymd'), 0);
        return $visitNum;
    }

    public function setVisitNum($key, $visitNum) {
        Cache::set($key. "_". date('Ymd'), $visitNum, 86400);
    }
}